package com.studentsystem.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {
    /**
     * token过期时间
     */
    public static final long EXPIRE = 7 * 60 * 60 * 24;
    /**
     * 密钥(由公司设置)
     */
    public static final String SECRET = "GH0Own1Special08Jwt30";

    public String getJwtToken(String username) {
        Map<String, Object> headers = new HashMap<>(4);
        headers.put("typ", "JWT");
        headers.put("alg", "HMAC256");

        return JWT.create()
                .withHeader(headers)
                .withSubject("system-user" + username)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE))
                //设置token主体部分
                .withClaim("username", username)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 根据token获取会员名
     */
    public String getUsernameByToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) {
            return null;
        }

        try {
            DecodedJWT jwt = JWT.decode(jwtToken);
            return jwt.getClaim("username").asString();
        } catch (Exception e) {
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            System.out.println(throwable.getMessage());
            return null;
        }
    }

    /**
     * 判断token是否存在或有效
     */
    public boolean checkToken(String jwtToken) {
        return getUsernameByToken(jwtToken) != null;
    }

    /**
     * 判断token是否存在或有效
     */
    public boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("Token");
            return getUsernameByToken(jwtToken) != null;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
